# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : process_version_option_view.py
# Time       ：2023/11/3 16:35
# Author     ：YangYong
# version    ：python 3.10
# Description：流程版本视图
"""
from flask import request
from flask_restx import fields
from sqlalchemy import desc

from apis.options import option_ns
from apis.options.schema.option_schema import OptionSchema
from apis.options.views import option_model
from apis.orderlines.models import Process
from public.api_utils.api_decorator import handle_api_error
from public.base_model import db
from public.base_response import generate_response, MarshalModel
from public.base_view import AbstractView

process_version_opt = {
    'process_id': fields.String(),
    'process_name': fields.String(),
}
process_version_opt_marshal = MarshalModel('process_version_opt', option_ns)


class ProcessVersionOptionView(AbstractView):
    url = '/process_version_opt'

    def __init__(self, *args, **kwargs):
        super(ProcessVersionOptionView, self).__init__(*args, **kwargs)
        self.form_data = request.args
        self.process_id = self.form_data.get('process_id')
        self.process_name = self.form_data.get('process_name')

    @handle_api_error()
    @option_ns.doc(description='流程版本选项')
    @option_ns.expect(process_version_opt_marshal.detail_request(process_version_opt))
    @option_ns.marshal_with(process_version_opt_marshal.list_response(option_model, as_list=True, is_db=False))
    def get(self):
        """流程版本选项"""
        if not self.process_id:
            objs = db.session.query(
                Process.version.label('label'),
                Process.process_id.label('value')
            ).filter(
                Process.active == 1,
                Process.version.isnot(None),
                Process.process_name == self.process_name
            ).all()
        else:
            objs = db.session.query(
                Process.version.label('label'),
                Process.process_id.label('value')
            ).filter(
                Process.active == 1,
                Process.version.isnot(None),
                Process.process_id == self.process_id
            ).order_by(desc(Process.id)).all()
        info = OptionSchema().dump(objs, many=True)
        return generate_response(info)
